package com.fantuan.weixin;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.CharEncoding;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.fantuan.weixin.bean.InMessage;
import com.fantuan.weixin.bean.InMessageText;
import com.fantuan.weixin.bean.OutMessage;

/**
 * 微信接口，根据内容进行分发
 * 
 * @author wangxinning
 * 
 */
public class PortalServlet extends HttpServlet {

	@Autowired
	@Qualifier("messageProcessingHandlerImpl")
	private MessageProcessingHandler messageProcess;
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -8514736857047992717L;

	public PortalServlet() {
		super();
	}

	//验证开发模式可用
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		/**
		 * 开发者模式验证逻辑
		 */
		String signature = request.getParameter( "signature" );
		String timestamp = request.getParameter( "timestamp" );
		String nonce = request.getParameter( "nonce" );
		String echostr = request.getParameter( "echostr" );

		if( StringUtils.isNotBlank(signature) && StringUtils.isNotBlank(timestamp)
				 && StringUtils.isNotBlank(nonce)
				 && StringUtils.isNotBlank(echostr))
		{
			IOUtils.write(echostr, response.getOutputStream());			
		}
		//开发者模式验证逻辑 END
	}

	/**
	 * 接收用户信息
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		response.setContentType("text/xml");

		//输入流
		ServletInputStream in = request.getInputStream();
		//转换为字符串
		String content = IOUtils.toString(in, CharEncoding.UTF_8);
		
		//实现处理接口
		InMessage inMessage = new InMessage( content );
		OutMessage outMessage = null;
		
		//文本消息
		if( StringUtils.equalsIgnoreCase(inMessage.getMsgType(),MessageProcessingHandler.MSG_TYPE_TEXT) )
		{
			InMessageText inMessageText = new InMessageText( content );
			outMessage = messageProcess.textTypeMsg(inMessageText);
		}
		
		//返回内容
		if( outMessage != null )
		{
			IOUtils.write(outMessage.toXML(), response.getOutputStream());
		}
	}
}